using System;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using Jbe.TestSuite.Infrastructure.Interface;
using Microsoft.Practices.CompositeUI.EventBroker;
using Jbe.TestSuite.TestDevice.SignalVisualizer.Constants;
using Jbe.TestSuite.TestDevice.Manager.Interface;
using Microsoft.Practices.CompositeUI.Utility;

namespace Jbe.TestSuite.TestDevice.SignalVisualizer.Views
{
    public partial class VisualizerViewPresenter : Presenter<IVisualizerView>
    {
        private bool startTimeSet = false;
        private DateTime startTime;
        
        public override void OnViewReady()
        {
            base.OnViewReady();
        }

        public void OnCloseView()
        {
            base.CloseView();
        }

        // [EventSubscription(EventTopicNames.Sample), Thread = ThreadOption.UserInterface)]
        // Bug in CAB: This throws an exception in EventBroker/Subscription/CallOnUserInterface
        //   if the application is closed and a timer thread is still active.
        // Workaround: Synchronize the calling thread inside the view implementation.
        [EventSubscription(EventTopicNames.Sample)]
        public void GotSample(object sender, SampleEventArgs sample)
        {
            if (!startTimeSet)
            {
                startTime = sample.TimeStamp;
                startTimeSet = true;
            }

            TimeSpan relativeTime = sample.TimeStamp.Subtract(startTime);

            View.AddSample(sender, sample.Amplitude, relativeTime.TotalMilliseconds / 10);
        }
    }
}

